from menu import Menu
from gameServer import gameServer
from eventServer import eventServer
from soundServer import sound

class MenuServer:
    def __init__(self):
        self.shownMenu = None
        self.menuStack = []
        self.menus = {}
        
        eventServer.register("showMenu",self.showMenuEvent)
        eventServer.register("popMenu",self.popMenuEvent)
        eventServer.register("hideAllMenus",self.hideAllEvent)
        
    def showMenuEvent(self, cmd, args):
        if args.has_key('menu'):
            self.showMenu(args['menu'])
            
    def popMenuEvent(self, cmd, args):
        self.popMenu()
        
    def hideAllEvent(self, cmd, args):
        self.hideAll()
        
    def loadMenu(self, menuName):
        if self.menus.has_key(menuName):
            return self.menus[menuName]
        else:
            menu = gameServer.addObject(menuName,Menu())
            menu.load(menuName + '.yml')
            menu.setVar('shown',False)
            self.menus[menuName] = menu
            return menu
        
    def showMenu(self, menuName, popping = False):
        if menuName in self.menuStack or menuName == self.shownMenu:
            return
        
        menu = self.loadMenu(menuName)
        
        if menu.hasVar("music"):
            sound.play(menu.getVar("music"),True)
        
        if self.shownMenu and not popping:
            self.menuStack.append(self.shownMenu)
            
        print "showMenu", menuName, self.menuStack
        
        for key, val in self.menus.iteritems():
            if key != menuName:
                val.setVar("shown",False)
        
        self.shownMenu = menuName
        menu.setVar('shown',True)
        eventServer.pull('initMenu',{})
        
    def popMenu(self):
        print "popMenu", self.menuStack
        if self.menuStack:
            self.showMenu(self.menuStack.pop(),True)
        else:
            print "hideAll"
            self.hideAll()
            
    def hideAll(self):
        for menu in self.menus.itervalues():
            menu.setVar("shown",False)
        self.shownMenu = None
        self.menuStack = []
        
    def anyMenusShown(self):
        return len(self.menuStack) > 0 or self.shownMenu
        
menuServer = MenuServer()
